package com.fjnu.dao.impl;

import com.fjnu.dao.CategoryDao;
import com.fjnu.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class CategoryDaoImpl implements CategoryDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    private final CategoryRowMapper categoryRowMapper = new CategoryRowMapper();

    @Override
    public int insert(Category category) {
        if(category.getName() == null || category.getParentId() == null)
            return 0;
        String sql = "INSERT INTO tb_category (name, `order`, parent_id, create_time, update_time) " +
                "VALUES (?, ?, ?, NOW(), NOW())";
        return jdbcTemplate.update(sql,
                category.getName(),
                category.getOrder(),
                category.getParentId());
    }

    @Override
    public int delete(Integer categoryId) {
        String sql = "DELETE FROM tb_category WHERE id = ?";
        return jdbcTemplate.update(sql, categoryId);
    }

    @Override
    public List<Category> selectById(Integer categoryId) {
        String sql = "SELECT * FROM tb_category WHERE id = ?";
        return jdbcTemplate.query(sql, categoryRowMapper, categoryId);
    }

    @Override
    public List<Category> selectByName(String name) {
        String sql = "SELECT * FROM tb_category WHERE name = ?";
        // ... 查询实现
        return jdbcTemplate.query(sql, categoryRowMapper, name);
    }
    
    @Override
    public List<Category> selectAll() {
        String sql = "SELECT * FROM tb_category";
        return jdbcTemplate.query(sql, categoryRowMapper);
    }

    private static class CategoryRowMapper implements RowMapper<Category> {
        @Override
        public Category mapRow(ResultSet rs, int rowNum) throws SQLException {
            Category category = new Category();
            category.setId(rs.getInt("id"));
            category.setName(rs.getString("name"));
            category.setOrder(rs.getInt("order"));
            category.setParentId(rs.getInt("parent_id"));
            category.setCreateTime(rs.getTimestamp("create_time").toLocalDateTime());
            category.setUpdateTime(rs.getTimestamp("update_time").toLocalDateTime());
            return category;
        }
    }

}